<template>
  <div>
    <div class="person-info">
      <el-row align="middle">
        <el-col :span="8">
            <el-col :span="12" :offset="2">
              <AvatarImg :customerSex="detail.customerSex" :age="detail.age"></AvatarImg>
            </el-col>
            <el-col :span="12">
              <div style="padding: 0 20px;">
                <div style="font-weight: bold; font-size: 20px;">{{ detail.customerName }}</div>
                <div class="reg-tag" v-if="detail.hasArrearsOrder">欠</div>
              </div>
              
            </el-col>
        </el-col>
        <el-col :span="8">
          <el-row>
            病历号: {{ detail.customerHistorySickNum }}
          </el-row>
          <el-row>
            手机号: {{ detail.customerPhone }}
          </el-row>
        </el-col>
        <el-col :span="8">
          <el-row>
            <!-- 初诊复诊: 初诊 -->
          </el-row>
          <el-row>
            <!-- 预约项目: 洁治 -->
          </el-row>
        </el-col>
      </el-row>
    </div>
    <div class="project">
      <el-table
            :data="addProjectList"
            style="width: 100%"
            :header-cell-style="{background:'#fff', color:'#000'}"
            >
            <el-table-column
              v-for="(item) in MockColumns"
              :key="item.name"
              :prop="item.name"
              :label="item.lable"
              :width="item.name === 'toothBit' ? '120' : ''"
              align="center"
              >
              <template #default="scope">
                <div v-if="item.name === 'toothBit'" >
                  <div style="">
                    <ztooth 
                      :lTToolist="scope.row[item.name].leftTop" 
                      :rTToolist="scope.row[item.name].rightTop" 
                      :lBToolist="scope.row[item.name].leftBottom" 
                      :rBToolist="scope.row[item.name].rightBottom"
                      @getLeftData="(() => getLeftData(scope.$index))()"
                      @getRightData="(() => getRightData(scope.$index))()"
                      @getLeftBottomData="(() => getLeftBottomData(scope.$index))()"
                      @getRightBottomData="(() =>getRightBottomData(scope.$index))()"
                      ></ztooth>
                  </div>
                </div>
                <template v-else-if="item.name === 'doctorId'">
                  <el-select v-model="scope.row[item.name]" filterable placeholder="请选择" style="width: 100%">
                    <el-option
                      v-for="item in optionsDoctors"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"
                    />
                  </el-select>
                  <!-- {{getName(optionsDoctors, scope.row[item.name])}} -->
                </template>
                <template v-else-if="item.name === 'nurseId'">
                <el-select v-model="scope.row[item.name]" filterable placeholder="请选择" style="width: 100%">
                    <el-option
                      v-for="item in optionsNurse"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"
                    />
                  </el-select>
                  <!-- {{getName(optionsNurse, scope.row[item.name])}} -->
                </template>
                <template v-else-if="item.name === 'consultantId'">
                      <!-- {{getName(secondaryUserOptions, scope.row[item.name])}} -->
                      <el-select
                        v-model="scope.row[item.name]" 
                        filterable
                        placeholder="请选择"
                        style="width: 100%"
                        >
                        <el-option
                          v-for="item in secondaryUserOptions"
                          :key="item.id"
                          :label="item.name"
                          :value="item.id">
                        </el-option>
                      </el-select>
                    </template>
                <div v-else>{{scope.row[item.name]}}</div>
              </template>
            </el-table-column>
        </el-table>
        <div class="price">
          <!-- <span><div>欠费: </div><div class="price-num red-color">{{  '00.00'}}</div></span> -->
          <span><div>应付金额: </div><div class="price-num blue-color">{{ detail.originalPriceShow ||  '00.00'}}</div></span>
          <span><div>实付金额: </div><div class="price-num">{{ detail.amountMoneyShow || '00.00'}}</div></span>
        </div>

    </div>

    <div class="content">
      
        <el-form
            ref="ruleFormRef"
            :model="ruleForm"
            status-icon
            :rules="rules"
            label-width="120px"
            class="demo-ruleForm"
          >
            <el-form-item label="账单号" label-width="100px">
              <el-col :span="12">
                {{ruleForm.orderNum}}
              </el-col>
              
            </el-form-item>
            <el-form-item label="创建时间" prop="createTime" label-width="100px">
              <el-col :span="10">
                <el-date-picker
                  v-model="ruleForm.createTime"
                  type="datetime"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  placeholder="请选择时间"
                />
              </el-col>
              
            </el-form-item>
            <!-- <el-form-item label="医生" prop="age" label-width="100px">
              <el-col :span="10">
                <el-select v-model="ruleForm.createName" filterable placeholder="请选择" style="width: 100%">
                    <el-option
                      v-for="item in optionsDoctors"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"
                    />
                  </el-select>
              </el-col>
            </el-form-item>
            <el-form-item label="护士" prop="age" label-width="100px">
              <el-col :span="10">
                <el-select v-model="ruleForm.createName" filterable placeholder="请选择" style="width: 100%">
                    <el-option
                      v-for="item in optionsNurse"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"
                    />
                  </el-select>
                </el-col>
            </el-form-item>
            <el-form-item label="咨询师" label-width="100px">
              <el-col :span="10">
                <el-select v-model="ruleForm.createName" filterable placeholder="请选择" style="width: 100%">
                    <el-option
                      v-for="item in secondaryUserOptions"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"
                    />
                  </el-select>
                </el-col>
            </el-form-item>
            <el-form-item label="网电咨询师" label-width="100px">
              <el-col :span="10">
                <el-select v-model="ruleForm.createName" filterable placeholder="请选择" style="width: 100%">
                    <el-option
                      v-for="item in secondaryUserOptions"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"
                    />
                  </el-select>
                </el-col>
            </el-form-item> -->
            <el-form-item label="备注" label-width="100px">
              <el-col :span="10">
                <el-input
                    v-model="ruleForm.remark"
                    :rows="2"
                    type="textarea"
                    placeholder="请输入"
                  />
              </el-col>
              </el-form-item>
            
          </el-form>
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, onMounted, reactive, toRefs, watch } from 'vue';
import AvatarImg from '../../../../components/avatarImg/avatarImg.vue';
import { getName } from "../../../../usefn/getName"
import ztooth from "../../../../components/tooch/imgTooth.vue"
import { MockType, Doctors } from "../../../../types"
import type { FormInstance } from 'element-plus'
import { ElMessage } from 'element-plus'

import { getDoctorListAllAPi, getNurseListAllAPi, getConsultListAllAPi, } from '../../../../api/common'
import { getOrderDetailApi, updateOrderInfoApi } from '../../../../api/order'
import orderDiscountVue from '../../../system/orderDiscount/orderDiscount.vue';
export default defineComponent({
    name: "BillEdit",
    props: {
      OrderDetail: {
        type: Object as any
      }
    },
    setup(props, ctx) {
       // 新增表格结构
    const MockColumns = [
      {
        name: 'toothBit',
        lable: '牙位'
      },
      {
        name: 'itemName',
        lable: '项目名称'
      },
      // {
      //   name: 'projectCode',
      //   lable: '项目编码'
      // },
      {
        name: 'unit',
        lable: '单位'
      },
      {
        name: 'priceShow',
        lable: '单价'
      },
      {
        name: 'realPriceShow',
        lable: '金额'
      },
      {
        name: 'number',
        lable: '数量'
      },
      {
        name: 'doctorId',
        lable: '医生'
      },
      {
        name: 'nurseId',
        lable: '护士'
      },
      {
        name: 'consultantId',
        lable: '咨询师'
      },
    ]

     // 项目
    const addProjectList = ref<any[]>([])
    const getLeftData = (index: number) => {
      return (data: MockType[]) => {
        addProjectList.value[index].toothBit.leftTop = data
      }
    }
    const getRightData = (index:number) => {
      return (data: MockType[]) => {
        addProjectList.value[index].toothBit.rightTop = data
      }
    }

    const getLeftBottomData = (index:number) => {
      return (data: MockType[]) => {
        addProjectList.value[index].toothBit.leftBottom = data
      }
    }

    const getRightBottomData = (index: number) => {
      return (data: MockType[]) => {
        addProjectList.value[index].toothBit.rightBottom = data
      }
    }

    const optionsDoctors = ref([] as Doctors[])
    const optionsNurse = ref([] as Doctors[])
    const secondaryUserOptions = ref([] as Doctors[])

    const getDoctor = async() => {
      let res:any = await getDoctorListAllAPi({})
      console.log(res)
      optionsDoctors.value = res.data || []
    }

    const getNurse = async() => {
      let res:any = await getNurseListAllAPi({})
      console.log(res)
      optionsNurse.value = res.data || []
    }

    const getConsultUser = async() => {
      let res:any = await getConsultListAllAPi({})
      console.log(res)
      secondaryUserOptions.value = res.data || []
    }

    const order = reactive({
      detail: props.OrderDetail,
    })
    watch(() => props.OrderDetail, (newObj) => {
      console.log('改变了', newObj)
      order.detail = newObj

      addProjectList.value = order.detail.details
      ruleForm.orderNum = order.detail.orderNum
      ruleForm.createTime = order.detail.createTime
      ruleForm.remark = order.detail.remark
      console.log(order.detail)
    })
    
    
    const setOrder = () => {
      order.detail.details && order.detail.details.forEach((i:any) => {
        i.toothBit = JSON.parse(i.toothBit)
      })
      addProjectList.value = order.detail.details
    }
    setOrder()


    const ruleFormRef = ref<FormInstance>()
    const ruleForm = reactive({
      orderNum: order.detail.orderNum || '',
      createTime: order.detail.createTime || '',
      checkPass: '',
      age: '',
      time: '',
      remark: order.detail.remark || ''
    })


    const rules = reactive({
      pass: [{ required: true, message: '请选择收费人', trigger: 'blur' }],
      checkPass: [{ required: true, message: '请选择医生', trigger: 'blur' }],
      age: [{ required: true, message: '请选择护士', trigger: 'blur' }],
      createTime: [{ required: true, message: '时间不能为空', trigger: 'blur' }],
    })

    const updateOrderInfo = async() => {
      let list  = [] as any[]
      addProjectList.value.forEach(i => {
        list.push({
          id: i.id,
          doctorId: i.doctorId,
          nurseId: i.nurseId,
          consultantId: i.consultantId,
          netConsultantId: i.netConsultantId
        })
      })
      let params = {
        id: order.detail.id,
        createTime: ruleForm.createTime,
        remark: ruleForm.remark,
        details: list
      }

      if (!ruleFormRef.value) return
          await ruleFormRef.value.validate(async (valid, fields) => {
            if (valid) {
              let res:any = await updateOrderInfoApi(params)
              console.log(res)
              if(res.code === 0) {
                ElMessage.success('修改成功')
                ctx.emit('refreshList')
                ctx.emit('closeDiolog')
              }
            } else {
              console.log('error submit!', fields)
              ElMessage.error('校验未通过')
            }
      })

      console.log(params)
      // let res = await updateOrderInfoApi({
        
      // })
    }

    


    const getOrder = async(id: number) => {
      let res:any = await getOrderDetailApi({}, id)
      console.log(res)
    }


    onMounted(() => {
      getDoctor()
      getNurse()
      getConsultUser()
    })
    return {
      MockColumns,
      getName,
      addProjectList,
      getLeftData,
      getRightData,
      getLeftBottomData,
      getRightBottomData,

      optionsDoctors,
      optionsNurse,
      secondaryUserOptions,
      getOrder,
      updateOrderInfo,
      ...toRefs(order),

      ruleFormRef,
      ruleForm,
      rules
    }
    },
    components: { AvatarImg, ztooth }
})
</script>

<style lang="scss" scoped>
  .person-info {
    padding-bottom: 10px;
    border-bottom: 2px solid $mainColor;
  }

  .price {
    padding: 20px;
    display: flex;
    align-items: center;
    justify-content: flex-end;

    & > span {
      display: flex;
      align-items: center;
      padding: 0 10px;
    }

    .price-num {
      font-size: 20px;
      color: #67C23A;
      padding-left: 10px;
    }

    .blue-color {
      color: #409EFF;
    }

    .red-color {
      color: #F56C6C;
    }
  }
  .reg-tag {
    width: 22px;
    height: 22px;
    border-radius: 50%;
    background-color: #F56C6C;
    display: flex;
    align-items: center;
    justify-content: center;
    color: white;
  }

  .content {
    background-color: #f4f4f4;
    margin-top: 20px;
    padding: 20px 0
  }
</style>